package mm.controller;
import com.itheima.mm.base.BaseController;
import com.itheima.mm.common.GlobalConst;
import com.itheima.mm.entity.Result;
import com.itheima.mm.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author ：seanyang
 * @date ：Created in 2019/8/17
 * @description ：公共控制器
 * @version: 1.0
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController extends BaseController {



	@PostMapping("/upload")
	public Result upload(MultipartHttpServletRequest request) {
		try {
			Map<String, MultipartFile> fileMap = request.getFileMap();

			List<Map<String,String>> resultList = new ArrayList<>();

			Iterator<String> iterator = request.getFileNames();
			while (iterator.hasNext()){
				String fileName = iterator.next();

				MultipartFile multipartFile = request.getFile(fileName);
				log.debug("fileName-{}:{}-{}-{}",fileName,multipartFile.getOriginalFilename(),multipartFile.getName(),multipartFile.getSize());
				// 对文件名进行重命名,UUID+文件后缀(文件类型)
				String newFileName = UUID.randomUUID().toString().replace("-","");
				String fileType = fileName.substring(fileName.lastIndexOf('.'));
				fileName = newFileName+fileType;
				// 获取应用程序路径
				//String contexPath= request.getSession().getServletContext().getRealPath("/");

				String contexPath = ClassUtils.getDefaultClassLoader().getResource("public").getPath();
				log.info("contexPath:{}",contexPath);
				// 读取配置文件,获得上传图片的相对路径
				ResourceBundle resourceBundle = ResourceBundle.getBundle("app-config");
				String uploadDirPath= resourceBundle.getString("upload_path");
				// 读取文件数据，并保存到Web资源目录
				File uploadDir = new File(contexPath,uploadDirPath);
				// 构建本地存储的文件对象
				File uploadFile = new File(uploadDir,fileName);
				// 从上传文件项获取字节输入流，然后保存到指定的上传目录下
				InputStream inputStream = multipartFile.getInputStream();
				FileOutputStream fos = new FileOutputStream(uploadFile);
				// 通过IO工具存入磁盘
				IOUtils.copy(inputStream,fos);
				// 关闭流
				IOUtils.closeQuietly(fos);
				IOUtils.closeQuietly(inputStream);
				// 存入数据库的路径
				String saveDbPath = uploadFile.getAbsolutePath().replace(new File(contexPath).getAbsolutePath(),"");
				Map mapResult = new HashMap();
				// 以上传的文件组件名为key,数据库保存的相对路径为value
				mapResult.put(fileName,saveDbPath);
				resultList.add(mapResult);
			}
			return new Result(true,"上传成功",resultList);
		}catch (Exception ex){
			ex.printStackTrace();
			return new Result(false,"上传失败,"+ex.getMessage());
		}
	}
}
